﻿$(document).ready(function () {

    var _month = (new Date()).getMonth() + 1;
    if (_month <= 9) { _month = '0' + _month; }
    var time = (new Date()).getFullYear() + '-' + _month;
    var selectedMonth = (new Date()).getMonth() + 1;
    var selectedYear = (new Date()).getFullYear();
    LoadLocation();
    //$('input:checkbox').bootstrapSwitch();
    $("#location").on("change", function () {
        $('#doctors').val('').attr('selected', true);
        $('#doctors').trigger("change");
        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Appointment/GetDoctorList',
            contentType: "application/json",
            data: JSON.stringify({ LocId: $("#location").val() }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                $('#doctors').empty();
                if (res.length > 1)
                    $('#doctors').append($('<option id=""\/>').val('').text('(Select Doctor)'));
                for (var i = 0; i < res.length; i++) {
                    $('#doctors').append($('<option id="' + res[i].Id + '"\/>').val(res[i].Id).text(res[i].Detail));
                }
                if (res.length == 1) {
                    $('#doctors option#' + res[0].Id).prop("selected", true);
                    $('#doctors').trigger("change");
                }
            },
            error: function (xhr) { debugger; }
        });
    });
    $("#doctors").on("change", function () {
        $("#doctorName").html('');
        $("span.badge").remove();
        localStorage.setItem("DoctorInfo", JSON.stringify({ DocId: $(this).val(), LocId: $("#location").val() }));
        if ($("#doctors option:selected").val()) {
            $("div.responsive-calendar").css("display", "block");
            $("#sendNotification").parent().css("display", "block");
            SetCurrentDate();
            $.ajax({
                type: "POST",
                url: _AbsolutePath + 'Appointment/GetMonthlyAppointmentList',
                contentType: "application/json",
                data: JSON.stringify({ DocId: $(this).val(), LocId: $("#location").val(), Month: (new Date()).getMonth() + 1, Year: (new Date()).getFullYear() }),
                caller: arguments.callee.name,//gets currently running function name
                dataType: "json", //Cross domain call (even json also work)
                success: function (res) {
                    $(res[1].Value).each(function (index, item) {
                        res[1].Value[index] = new Date(item.split('/')[2],item.split('/')[1] - 1,item.split('/')[0]).toString();
                    });
                    if (res[0].Value.length > 0) localStorage.setItem("DocPersonalDet", JSON.stringify(res[0].Value[0]));
                    $(res[0].Value).each(function (index, val) {
                        var element = _.find($('a[data-month=' + ((new Date()).getMonth() + 1) + ']'), function (item) {
                            return $(item).attr('data-day') === (new Date(parseInt(val.Date.replace("/Date(", "").replace(")/", "")))).getDate().toString()
                        });
                        var _dateSelected = element.attributes["data-year"].value.toString()
                               + "-" + element.attributes["data-month"].value.toString() + "-" + element.attributes["data-day"].value.toString();
                       
                        $((element).parentNode).attr("onclick", "LoadApptDetails('" + _dateSelected + "')").addClass("pointer");
                        $((element).parentNode).html($((element).parentNode)[0].innerHTML +
                                    "<span class='badge'>" + val.Count + "</span>");
                        
                    });
                    $(".responsive-calendar > div.days > div > a").each(function (index, element) {
                        $(this).parent().append("<span class='glyphicon glyphicon-ban-circle dayoff' style='display:none;' aria-hidden='true'></span>");
                        var _dateSelected = element.attributes["data-year"].value.toString()
                               + "-" + element.attributes["data-month"].value.toString() + "-" + element.attributes["data-day"].value.toString();
                        if (_.some(res[1].Value, function (item) { return item == new Date(_dateSelected.split('-')[0], _dateSelected.split('-')[1] - 1, _dateSelected.split('-')[2]).toString() }))
                            $((element).parentNode).addClass("dayOff");
                    });
                    $(".responsive-calendar .day .glyphicon-ban-circle.dayoff").click(SetOrUnsetDayOff);
                    $("#doctorName").html("(" + $("#doctors option:selected").html() + ")");
                    
                },
                error: function (xhr) { }
            });
        }
        else {
            $("div.responsive-calendar").css("display", "none");
            $("#sendNotification").parent().css("display", "none");
        }
    });
    $("#chkSetDayoff").click(function () {
        $(".responsive-calendar .day .glyphicon-ban-circle.dayoff").fadeToggle();
    });
    $("#sendNotification").click(function () {
        alert("Notifications will be sent.");
        $.ajax({
            type: "POST",
            async: true,
            url: _AbsolutePath + 'Appointment/SendMonthNotification',
            contentType: "application/json",
            data: JSON.stringify({ DocId: $("#doctors > option:selected").val(), LocId: $("#location > option:selected").val(), Month: selectedMonth, Year: selectedYear, doctorName: $("#doctors > option:selected").html() }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                
            },
            error: function (xhr) { }

        });
    });

    var _calender = $(".responsive-calendar").responsiveCalendar({
        time: time,
        onDayClick: function (e) {
            var _selectedDate = this.attributes["data-year"].value.toString()
                           + "-" + ('0' + this.attributes["data-month"].value.toString()).slice(-2) + "-" + ('0' + this.attributes["data-day"].value.toString()).slice(-2);
            if(!$($(this).parent()).hasClass("dayOff"))
                LoadApptDetails(_selectedDate);
        },
        onMonthChange: function (ev, data) {



            if (this.currentMonth == 12) {
                selectedMonth = 1;
                selectedYear = this.currentYear + 1;
            } else {
                selectedMonth = this.currentMonth + 1;
                selectedYear = this.currentYear;
            }
            LoadNoOfAppts(selectedMonth, selectedYear);
            setTimeout(function () { 
               
            },100);
        }
    });
});

function LoadNoOfAppts(month, year) {
    $.ajax({
        type: "POST",
        url: _AbsolutePath + 'Appointment/GetMonthlyAppointmentList',
        contentType: "application/json",
        data: JSON.stringify({ DocId: $('#doctors').val(), LocId: $("#location").val(), Month: month , Year: year }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            setTimeout(function () {
                $(res[1].Value).each(function (index, item) {
                    res[1].Value[index] = new Date(item.split('/')[2], item.split('/')[1] - 1, item.split('/')[0]).toString();
                });
                if (res[0].Value.length > 0) localStorage.setItem("DocPersonalDet", JSON.parse(JSON.stringify(res[0].Value[0])));
                $(res[0].Value).each(function (index, val) {
                    var element = _.find($('a[data-month=' + month + ']'), function (item) {
                        return $(item).attr('data-day') === (new Date(parseInt(val.Date.replace("/Date(", "").replace(")/", "")))).getDate().toString()
                    });
                    var _dateSelected = element.attributes["data-year"].value.toString()
                           + "-" + element.attributes["data-month"].value.toString() + "-" + element.attributes["data-day"].value.toString();
                    
                        $((element).parentNode).attr("onclick", "LoadApptDetails('" + _dateSelected + "')").addClass("pointer");
                    $((element).parentNode).html($((element).parentNode)[0].innerHTML +
                                "<span class='badge'>" + val.Count + "</span>");
                });
                $(".responsive-calendar > div.days > div > a").each(function (index, element) {
                    $(this).parent().append("<span class='glyphicon glyphicon-ban-circle dayoff' style='display:none;' aria-hidden='true'></span>");
                    var _dateSelected = element.attributes["data-year"].value.toString()
                           + "-" + element.attributes["data-month"].value.toString() + "-" + element.attributes["data-day"].value.toString();
                    if (_.some(res[1].Value, function (item) { return item == new Date(_dateSelected.split('-')[0], _dateSelected.split('-')[1] - 1, _dateSelected.split('-')[2]).toString() }))
                        $((element).parentNode).addClass("dayOff");
                });
                $(".responsive-calendar .day .glyphicon-ban-circle.dayoff").click(SetOrUnsetDayOff);
                $("#doctorName").html("(" + $("#doctors option:selected").html() + ")");
                SetCurrentDate();
                if ($("#chkSetDayoff").is(":checked")) $(".responsive-calendar .day .glyphicon-ban-circle.dayoff").fadeIn();
            }, 1000);
        },
        error: function (xhr) { }
    });

}

function LoadApptDetails(_date1) {
    var _dateSelected = "";
    if (environment == "prod") {
        _dateSelected = _date1.split('-')[1] + "/" + _date1.split('-')[2] + "/" + _date1.split('-')[0];
    } else {
        _dateSelected = _date1.split('-')[2] + "/" + _date1.split('-')[1] + "/" + _date1.split('-')[0];
    }
    $.ajax({
        type: "POST",
        url: _AbsolutePath + 'Appointment/AddDoctorDetails',
        contentType: "application/json",
        data: JSON.stringify({ DocId: $('#doctors').val(), LocId: $("#location").val(), date: _dateSelected}),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            SelectedDate = _date1;
            localStorage.setItem("selectedDate", _date1.split('-')[0] + ',' + (parseInt(_date1.split('-')[1]) - 1) + ',' + _date1.split('-')[2]);
            location.href = _AbsolutePath + "Appointment/AppointmentDetail";
        },
        error: function (xhr) {
            
        }
    });
}

function LoadLocation() {
    $.ajax({
        type: "POST",
        url: _AbsolutePath + 'Appointment/GetLocationList',
        contentType: "application/json",
        dataType: "json", //Cross domain call (even json also work)
        data: JSON.stringify({ clinicCode: localStorage.getItem("ClinicCode") }),
        success: function (res) {
            
            $('#location').empty();
            if (res.length > 1)
                $('#location').append($('<option id=""\/>').val('').text('(Select Location)'));
            for (var i = 0; i < res.length; i++) {
                $('#location').append($('<option id="' + res[i].Id + '"\/>').val(res[i].Id).text(res[i].Detail));
            }
            if (res.length == 1) {
                $('#location option#' + res[0].Id).prop("selected", true);
                $('#location').trigger("change");
            }
        },
        error: function (xhr) {  }
    });
}

function SetCurrentDate() {
    $($("a[data-day=" + new Date().toString("dd") + "][data-month = " + new Date().toString("MM") + "]").parent()).css("background-color", "#428bca");
}

function SetOrUnsetDayOff() {
    var selectedIcon = $(this);
    selectedIcon.prop("disabled", true);
    var element = $(this).parent().find("a")[0];
    var dateOff;
    if (environment == "prod")
        dateOff = element.attributes["data-month"].value.toString()
               + "/" + element.attributes["data-day"].value.toString() + "/" + element.attributes["data-year"].value.toString()
    else
        dateOff = element.attributes["data-day"].value.toString()
               + "/" + element.attributes["data-month"].value.toString() + "/" + element.attributes["data-year"].value.toString()
    if (!selectedIcon.parent().hasClass("dayOff")) {
        $.ajax({
            type: "POST",
            async: true,
            url: _AbsolutePath + 'Appointment/SaveDoctorDayOff',
            contentType: "application/json",
            data: JSON.stringify({
                dateOff: dateOff,
                DocId: $("#doctors > option:selected").val()
            }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                //if (selectedIcon.parent().hasClass("dayOff")) $(this).parent().removeClass("dayOff");
                selectedIcon.parent().addClass("dayOff");
                selectedIcon.prop("disabled", false);
            },
            error: function (xhr) { alert("Not able to set dayoff.") }

        });
    }
    else {
        $.ajax({
            type: "POST",
            async: true,
            url: _AbsolutePath + 'Appointment/DeleteDoctorDayOff',
            contentType: "application/json",
            data: JSON.stringify({
                dateOff: dateOff,
                DocId: $("#doctors > option:selected").val()
            }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                selectedIcon.parent().removeClass("dayOff");
                //else selectedIcon.parent().addClass("dayOff");
                selectedIcon.prop("disabled", false);
            },
            error: function (xhr) { alert("Not able to set dayoff.") }

        });
    }
}